import { AfterViewInit, Directive, ElementRef, Input, NgZone, OnChanges, OnDestroy, SimpleChanges } from '@angular/core';
import { NzSelectComponent } from 'ng-zorro-antd';
import { LoggerService } from '../../../core/service/logger.service';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'nz-select'
})
export class NzSelectDirective implements AfterViewInit, OnChanges, OnDestroy {

  Ele_P;
  observer;
  listOfSelectedValue;
  addOrRemove = 0; // add:1;remove:-1;default:0;
  /**
   * 是否单行显示选中的文本,默认单行
   */
  _bzSingleLine;
  @Input() set bzSingleLine(v) {
    if (v === false) {
      this._bzSingleLine = v;
    } else {
      this._bzSingleLine = true;
    }
  }
  get bzSingleLine() {
    return this._bzSingleLine;
  }
  @Input() ngModel;
  @Input() name;

  constructor(
    private selectComponent: NzSelectComponent,
    private el: ElementRef,
    private ngZone: NgZone,
    private logger: LoggerService
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.selectComponent.nzSelectService.isMultipleOrTags && this.bzSingleLine === true) {
      // tslint:disable-next-line:max-line-length
      if (!changes.ngModel.firstChange && changes.ngModel.previousValue && Array.isArray(changes.ngModel.previousValue) && changes.ngModel.previousValue.length > 0 && changes.ngModel.currentValue && Array.isArray(changes.ngModel.currentValue) && changes.ngModel.currentValue.length > 0) {
        this.addOrRemove = changes.ngModel.currentValue.length - changes.ngModel.previousValue.length;
      } else {
        this.addOrRemove = 0;
      }
    }
  }

  ngAfterViewInit(): void {
    if (this.selectComponent.nzSelectService.isMultipleOrTags && this.bzSingleLine === true) {
      // this.logger.warn(`bzName:${this.name},补丁（NzSelectDirective）多选模式下内容不换行`);
      this.Ele_P = this.el.nativeElement.querySelector('.ant-select-selection--multiple .ant-select-selection__rendered ul');
      this.ngZone.runOutsideAngular(() => {
        this.observer = new MutationObserver(this.eventDom);
        this.observer.observe(this.Ele_P, {
          childList: true
        });
      });
      this.selectComponent.nzSelectService.listOfSelectedValue$.subscribe(e => {
        this.listOfSelectedValue = e;
      });
    }
    if (this.selectComponent.nzSelectService.isSingleMode && this.selectComponent.nzSelectTopControlComponent.nzShowSearch) {
      // this.logger.warn(`bzName:${this.name},补丁（NzSelectDirective）单选模式，搜索时在原有选中文本上编辑搜索`);
      this.selectComponent.nzSelectService.open$.subscribe(e => {
        this.ngZone.runOutsideAngular(() => {
          setTimeout(() => {
            const selectedDiv = this.el.nativeElement.querySelector('.ant-select-selection-selected-value');
            if (e === true) {
              const activatedOption = this.selectComponent.nzSelectService.activatedOption ? this.selectComponent.nzSelectService.activatedOption.nzLabel : '';
              // this.selectComponent.nzSelectTopControlComponent.setInputValue(activatedOption);
              this.selectComponent.nzSelectTopControlComponent.inputElement.nativeElement.value = activatedOption;
              if (selectedDiv) {
                selectedDiv.style.visibility = 'hidden';
              }
            } else {
              if (selectedDiv) {
                selectedDiv.style.visibility = 'visible';
              }
            }
          });
        });
      });
    }
  }

  // DOM变更回调函数
  eventDom = (mutationsList, observer) => {
    for (const mutation of mutationsList) {
      if (mutation.type === 'childList') {
        if (mutation.addedNodes[0] && mutation.addedNodes[0].nodeName === 'LI' && (this.addOrRemove === 0 || this.addOrRemove === -1)) {
          mutation.addedNodes[0].style.display = 'none';
        }
        // tslint:disable-next-line:max-line-length
        if ((mutation.addedNodes[0] && mutation.addedNodes[0].nodeName === 'LI' && (this.addOrRemove === 0 || this.addOrRemove === 1)) || (mutation.removedNodes[0] && mutation.removedNodes[0].nodeName === 'LI' && (this.addOrRemove === 0 || this.addOrRemove === -1))) {
          const liE = this.Ele_P.querySelectorAll('li');
          if (this.listOfSelectedValue.length > 0) {
            this.updateDisable(liE);
          }
        }
      }
    }
  }

  // 多选模式下优化显示内容，达到不换行效果
  updateDisable(liE?) {
    const maxTagCount = this.selectComponent.nzMaxTagCount + 2;
    const num = liE.length;
    let width = 'auto';
    width = num === 2 ? width : `calc((88% - ${4 * num}px) / ${num})`;
    for (let i = 0; i < liE.length; i++) {
      liE[i].style.cssText = `width:${width};display:list-item`;
    }
    if (maxTagCount === num) {
      liE[liE.length - 2].style.padding = '0 0 0 5px';
    }
  }

  ngOnDestroy(): void {
    if (this.observer) {
      this.observer.disconnect();
    }
  }
}
